import 'package:bruno/bruno.dart';
import 'package:common/common.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:miaowu/app/module/mine/audio_card/container_tab_indicator.dart';
import 'package:miaowu/app/theme/font.dart';

import 'user_tags_config.dart';

class UserEditTagsPage extends StatefulWidget {
  const UserEditTagsPage({super.key});

  @override
  State<UserEditTagsPage> createState() => _UserEditTagsPageState();
}

class _UserEditTagsPageState extends State<UserEditTagsPage> with TickerProviderStateMixin {
  late TabController _tabController;
  final List<Widget> _pages = [];

  final List<String> _tabs = [];
  UsertagsConfigData? userTagsConfig;

  List<String> chooseUserTags = [];

  @override
  void initState() {
    super.initState();
    fetchEditTagsConfig();
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  void fetchEditTagsConfig() {
    HttpProvider.get(
      '/user/getEditTagsInit',
      explain: '获取编辑标签初始化数据',
      success: (result) {
        UsertagsConfigData config = UsertagsConfigData.fromJson(result.data);
        userTagsConfig = config;
        chooseUserTags = userTagsConfig?.list ?? [];
        UserTagSingleton.chooseUserTags = chooseUserTags;

        for (TagOptions element in userTagsConfig!.options!) {
          _tabs.add(element.tags!);
          _pages.add(UserTagsOptionsPage(
            key: PageStorageKey(element.tags),
            subs: element.subs ?? [],
            callBack: (value) {
              chooseUserTags = value;
              UserTagSingleton.chooseUserTags = chooseUserTags;
              setState(() {});
            },
          ));
        }
        _tabController = TabController(length: _pages.length, vsync: this);
        setState(() {});
      },
    );
  }

  void fetchSubmitEditInfo() {
    HttpProvider.post(
      '/user/subEditTags',
      params: {'tags': UserTagSingleton.chooseUserTags.join('|')},
      explain: '用户提交编辑信息',
      success: (result) {
        Toast.showText(result.message);
      },
      failure: (result) {
        Toast.showText(result.message);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xFFF0F0F0),
      child: SafeArea(
        top: false,
        bottom: false,
        child: Scaffold(
          appBar: BrnAppBar(
            title: '    个人标签',
            centerTitle: false,
            backgroundColor: Colors.transparent,
            actions: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 8),
                child: BrnSmallMainButton(
                  width: 50,
                  title: "保存",
                  bgColor: const Color(0xFF25D4D0),
                  themeData: BrnButtonConfig(smallButtonHeight: 15.h, smallButtonFontSize: 12, smallButtonRadius: 13.r),
                  insertPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 1),
                  onTap: () {
                    fetchSubmitEditInfo();
                  },
                ),
              )
            ],
          ),
          backgroundColor: Colors.transparent,
          body: userTagsConfig == null
              ? const Center(child: CupertinoActivityIndicator())
              : Container(
                  padding: EdgeInsets.symmetric(horizontal: 0.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 32.h),
                      Container(
                          margin: const EdgeInsets.only(top: 10, bottom: 20),
                          padding: const EdgeInsets.symmetric(horizontal: 12),
                          child: Wrap(
                            crossAxisAlignment: WrapCrossAlignment.center,
                            alignment: WrapAlignment.start,
                            spacing: 10,
                            runSpacing: 10,
                            children: chooseUserTags
                                .map((e) => _buildItem(title: e, chooseUserTags: chooseUserTags))
                                .toList(),
                          )),
                      Container(
                        alignment: Alignment.centerRight,
                        padding: EdgeInsets.symmetric(horizontal: 12.w),
                        margin: EdgeInsets.only(bottom: 20.h),
                        child: Text.rich(
                            TextSpan(style: TextStyle(fontSize: 12.sp, color: const Color(0xFF000000)), children: [
                          TextSpan(
                              text: chooseUserTags.length.toString(), style: const TextStyle(color: Color(0xFF25D4D0))),
                          TextSpan(text: '/${userTagsConfig!.tagsMaxNum}'),
                        ])),
                      ),
                      Expanded(
                        child: Container(
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius:
                                  BorderRadius.only(topLeft: Radius.circular(16.r), topRight: Radius.circular(16.r))),
                          child: Column(
                            children: [
                              const SizedBox(height: 16),
                              Container(
                                height: 44,
                                color: Colors.amber,
                                child: _tabbarWarpper(),
                              ),
                              Expanded(
                                child: TabBarView(
                                    controller: _tabController,
                                    children: _pages.map((e) {
                                      return e;
                                    }).toList()),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
        ),
      ),
    );
  }

  Widget _buildItem({required String title, required List<String> chooseUserTags}) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if (chooseUserTags.contains(title)) {
          chooseUserTags.remove(title);
        } else {
          chooseUserTags.add(title);
        }
        UserTagSingleton.chooseUserTags = chooseUserTags;
        bus.post(eventName: 'user_tag_refsh', data: title);
        setState(() {});
      },
      child: Container(
          decoration:
              BoxDecoration(color: const Color(0xFFFFFFFF), borderRadius: BorderRadius.all(Radius.circular(18.r))),
          padding: const EdgeInsets.symmetric(horizontal: 15), //
          child: Container(
            // alignment: Alignment.center,
            color: Colors.transparent,
            padding: const EdgeInsets.only(top: 6, bottom: 6),
            child: Text.rich(TextSpan(
                style: TextStyle(fontSize: 16.sp, color: const Color(0xFF333333), fontWeight: FontWeight.w600),
                children: [
                  TextSpan(text: title),
                  WidgetSpan(
                      alignment: PlaceholderAlignment.middle,
                      child: Padding(
                        padding: const EdgeInsets.only(left: 10),
                        child: Image.asset('assets/app/images/mine/user_tag_del.png', width: 9),
                      )),
                ])),
          )),
    );
  }

  Widget _tabbarWarpper() {
    return DefaultTabController(
      length: _pages.length,
      child: Container(
        color: Colors.white,
        // height: 40,
        child: TabBar(
          tabAlignment: TabAlignment.start,
          controller: _tabController,
          labelColor: const Color(0xFF222222),
          indicatorColor: Colors.black,
          unselectedLabelColor: const Color(0xFF222222),
          isScrollable: true,
          indicatorWeight: 0,
          overlayColor: WidgetStateProperty.resolveWith((states) {
            return Colors.transparent;
          }),
          dividerHeight: 0,
          indicator: ContainerTabIndicator(
              color: const Color(0xFF22F2EB),
              width: 30.w,
              height: 3.w,
              radius: const BorderRadius.all(Radius.circular(14.0)),
              padding: const EdgeInsets.only(left: 0.0, right: 0, top: 15, bottom: 0)),
          labelStyle: const TextStyle(color: Color(0xFF22F2EB), fontSize: 15, fontWeight: AppFontWeight.semiBold),
          unselectedLabelStyle: const TextStyle(color: Color(0xFF222222), fontSize: 15),
          onTap: (index) {
            logs(index);
          },
          tabs: List.generate(_tabs.length, (index) {
            // return Tab(text: _tabs[index]);
            return Tab(child: Text(_tabs[index]));
          }),
        ),
      ),
    );
  }
}

class UserTagsOptionsPage extends StatefulWidget {
  UserTagsOptionsPage({
    super.key,
    required this.subs,
    required this.callBack,
  });
  List<TagSubs> subs;
  Function callBack;

  @override
  State<UserTagsOptionsPage> createState() => _UserTagsOptionsPageState();
}

class _UserTagsOptionsPageState extends State<UserTagsOptionsPage> {
  @override
  void initState() {
    super.initState();

    bus.on('user_tag_refsh', runtimeType: runtimeType, hashCode: hashCode, callback: (event) {
      setState(() {});
    });
  }

  @override
  void dispose() {
    bus.cancelBySubscriber(runtimeType, hashCode: hashCode);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: const EdgeInsets.only(top: 10),
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: Wrap(
          crossAxisAlignment: WrapCrossAlignment.center,
          alignment: WrapAlignment.start,
          spacing: 10,
          runSpacing: 10,
          children: widget.subs.map((e) => _buildItem(title: e.title ?? '')).toList(),
          // children: widget.tabs.map((e) => _buildItem(title: e)).toList(),
        ));
  }

  Widget _buildItem({required String title}) {
    bool isSel = UserTagSingleton.chooseUserTags.contains(title);
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if (UserTagSingleton.chooseUserTags.contains(title)) {
          UserTagSingleton.chooseUserTags.remove(title);
        } else {
          if (UserTagSingleton.chooseUserTags.length >= 10) {
            return;
          }
          UserTagSingleton.chooseUserTags.add(title);
        }
        setState(() {});
        widget.callBack(UserTagSingleton.chooseUserTags);
      },
      child: Container(
          height: 36,
          // margin: const EdgeInsets.symmetric(horizontal: 5),
          decoration: isSel
              ? BoxDecoration(
                  color: const Color(0xFFD9FFFE),
                  border: Border.all(color: const Color(0xFF25D4D0), width: 1),
                  borderRadius: BorderRadius.all(Radius.circular(18.r)))
              : BoxDecoration(color: const Color(0xFFF6F6F6), borderRadius: BorderRadius.all(Radius.circular(18.r))),
          padding: const EdgeInsets.symmetric(horizontal: 15), //
          child: Container(
            // alignment: Alignment.center,
            color: Colors.transparent,
            padding: const EdgeInsets.only(top: 6),
            child: Text(title,
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 16,
                    color: isSel ? const Color(0xFF25D4D0) : const Color(0xFF333333),
                    fontWeight: isSel ? FontWeight.w600 : FontWeight.w500)),
          )),
    );
  }
}

/// 单例

class UserTagSingleton {
  static UserTagSingleton? _instance;
  // Avoid self instance
  UserTagSingleton._();
  static UserTagSingleton get instance {
    _instance ??= UserTagSingleton._();
    return _instance!;
  }

  static List<String> chooseUserTags = [];
}
